from sys import stdout
from urllib import urlretrieve
from os.path import isfile
from os import remove
from re import compile


class Downloader(object):
    def __init__(self, filename, urls):
        n = compile(r'^(.*)\.([a-zA-Z0-9]*)$').findall(filename)[0]
        self.__basename = n[0]
        self.__extname = n[1]
        self.__urls = urls
        
    @staticmethod
    def __cb(blknum, blksize, fsize):
        dl = blknum * blksize
        stdout.write('\r%d/%d, %d%%' %(dl, fsize, dl * 100 / fsize))

    def download(self):
        print 'Download', self.__basename
        m3u = self.__basename + '.m3u'
        if isfile(m3u): remove(m3u)
        fm3u = open(m3u, 'wb')
        for i in range(0, len(self.__urls)):
            item = '%s_seg%02d.%s\n'%(self.__basename, i, self.__extname)
            fm3u.write(item);
        fm3u.close()
        
        i = 0
        for url in self.__urls:
            print('Donload segment %d' % (i))
            fname = self.__basename + '_seg%02d.%s'%(i, self.__extname)
            if isfile(fname): remove(fname)
            urlretrieve(url, fname, Downloader.__cb)
            print('')
            i += 1             
